package net.sf.odinms.net.channel.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import net.sf.odinms.client.Equip;
import net.sf.odinms.client.IItem;
import net.sf.odinms.client.Item;
import net.sf.odinms.client.MapleCharacter;
import net.sf.odinms.client.MapleClient;
import net.sf.odinms.client.MapleInventory;
import net.sf.odinms.client.MapleInventoryType;
import net.sf.odinms.net.AbstractMaplePacketHandler;
import net.sf.odinms.database.DatabaseConnection;
import net.sf.odinms.net.MapleServerHandler;
import net.sf.odinms.server.MapleInventoryManipulator;
import net.sf.odinms.tools.MaplePacketCreator;
import net.sf.odinms.tools.data.input.SeekableLittleEndianAccessor;

/**
*
* @author Bassoe
*/
public class MTSHandler extends AbstractMaplePacketHandler {
	private final static Logger log = LoggerFactory.getLogger(MapleServerHandler.class);
	
	@Override
	public void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {
		int action = slea.readByte();
                if (action == 2) {//sell               
                    //log.info(slea.toString());
                    if (c.getPlayer().getMeso() < 5000) {
                        return;
                    }
                    try {
                        int type = slea.readByte();
                        boolean etc = false;
                        if (type == 2) {
                            Connection con = DatabaseConnection.getConnection();
                            PreparedStatement ps = con.prepareStatement("INSERT INTO mtsitems (itemid, type, price, sellerid, quantity, selleraccountname, sellercharname, position) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                            etc = true;
                        }
                        Connection con = DatabaseConnection.getConnection();
                        PreparedStatement ps = con.prepareStatement("INSERT INTO mtsitems (itemid, type, price, upgradeslots, level, str, dex, `int`, luk, hp, mp, watk, matk, wdef, mdef, acc, avoid, hands, speed, jump, sellerid, quantity, selleraccountname, sellercharname, position, owner) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        int itemId = slea.readInt();
                        ps.setInt(1, itemId);//itemid
                        ps.setInt(2, type);//type
                        slea.readShort();
                        slea.readByte();//ITEM_MAGIC
                        slea.readByte();//5?
                        slea.readInt();//time
                        slea.readByte();//showtime
                        if (!etc) {
                            ps.setInt(4, slea.readByte());//upgradeslots
                            ps.setInt(5, slea.readByte());//level
                            ps.setInt(6, slea.readShort());//str
                            ps.setInt(7, slea.readShort());//dex
                            ps.setInt(8, slea.readShort());//int
                            ps.setInt(9, slea.readShort());//luk
                            ps.setInt(10, slea.readShort());//hp
                            ps.setInt(11, slea.readShort());//mp
                            ps.setInt(12, slea.readShort());//watk
                            ps.setInt(13, slea.readShort());//matk
                            ps.setInt(14, slea.readShort());//wdef
                            ps.setInt(15, slea.readShort());//mdef
                            ps.setInt(16, slea.readShort());//acc
                            ps.setInt(17, slea.readShort());//avoid
                            ps.setInt(18, slea.readShort());//hands
                            ps.setInt(19, slea.readShort());//speed
                            ps.setInt(20, slea.readShort());//jump
                            ps.setInt(21, c.getPlayer().getId());
                            ps.setInt(22, 1);
                            ps.setString(23, c.getAccountName());
                            ps.setString(24, c.getPlayer().getName());
                            String owner = slea.readMapleAsciiString();//owner
                            slea.readShort();//0
                            slea.readInt();//mts item id - B9 B3 16 01
                            slea.readInt();//unknown - 00 00 00 7C
                            int position = slea.readInt();
                            int quantity = slea.readInt();
                            ps.setInt(25, position);
                            ps.setString(26, owner);
                            int price = slea.readInt();
                            slea.readShort();
                            ps.setInt(3, price);
                            MapleInventoryManipulator.removeById(c, MapleInventoryType.getByType((byte)type), itemId, 1, true, false);
                        } else {
                            ps.setInt(4, c.getPlayer().getId());
                            int quantity = slea.readShort();
                            ps.setInt(5, quantity);
                            ps.setString(6, c.getAccountName());
                            ps.setString(7, c.getPlayer().getName());
                            int bundles = slea.readInt();
                            slea.readInt();
                            int position = slea.readInt();
                            int price = slea.readInt();
                            slea.readShort();
                            ps.setInt(8, position);
                            ps.setInt(3, price);
                            MapleInventoryManipulator.removeById(c, MapleInventoryType.getByType((byte)type), itemId, quantity, true, false);
                        }
                        ps.executeUpdate();
                        ps.close();
                        c.getPlayer().gainMeso(-5000, false);
                        c.getSession().write(MaplePacketCreator.getMTSUpdate());
                        c.getSession().write(MaplePacketCreator.getMTSNotYet(c.getPlayer()));
                        c.getSession().write(MaplePacketCreator.getMTSItems(c.getPlayer(), 1, 0));
                    } catch (SQLException se) {
                        log.info("error inserting mts item", se);
                    }
                } else if (action == 4) {//cancel sale from auctions
                    int mtsitemid = slea.readInt();
                    slea.readInt();
                    int quantity = slea.readInt();
                    slea.readShort();
                    String comment = slea.readMapleAsciiString();
                } else if (action == 5) {//switch pages
                    int tab = slea.readInt();
                    slea.readInt();
                    int page = slea.readInt();
                    slea.readByte();//dunno what, but its 1 o.o
                    slea.readByte();//dunno what, but its 1 o.o
                    slea.readByte();//dunno what, but its 1 o.o
                    slea.readByte();//dunno what, but its 0 o.o
                    slea.readInt();
                    c.getSession().write(MaplePacketCreator.getMTSItems(c.getPlayer(), tab, page));
                } else if (action == 7) {//cancel sale
                    int mtsitemid = slea.readInt();
                    try { // MTS: created by Bassoe
                        Connection con = DatabaseConnection.getConnection();
                        PreparedStatement ps = con.prepareStatement("UPDATE mtsitems SET transfer = 1 WHERE mtsitemid = ?");
                        ps.setInt(1, mtsitemid);
                        ps.executeUpdate();
                        c.getSession().write(MaplePacketCreator.getMTSNotYet(c.getPlayer()));
                        c.getSession().write(MaplePacketCreator.getMTSTransfer(c.getPlayer()));
                        c.getSession().write(MaplePacketCreator.getMTSItems(c.getPlayer(), 1, 0));
                        ps.close();
                    } catch (SQLException e) {
                        log.info("eh", e);
                    }
                } else if (action == 8) {//transfer item
                    int mtsitemid = slea.readInt();
                    try { // MTS: created by Bassoe
                        Connection con = DatabaseConnection.getConnection();
                        PreparedStatement ps = con.prepareStatement("SELECT * FROM mtsitems WHERE mtsitemid = ? AND transfer = 1");
                        ps.setInt(1, mtsitemid);
                        ResultSet rs = ps.executeQuery();
                        while (rs.next()) {
                            if (rs.getInt("type") == 1) {
                                MapleInventory lol = new MapleInventory(MapleInventoryType.EQUIP , (byte) 100);
                                Equip equip = new Equip(rs.getInt("itemid"), (byte) lol.getNextFreeSlot(), (short) -1);
                                if (rs.getString("owner") != null) {
                                    equip.setOwner(rs.getString("owner"));
                                }
                                equip.setStr((short)rs.getInt("str"));
                                equip.setDex((short)rs.getInt("dex"));
                                equip.setInt((short)rs.getInt("int"));
                                equip.setLuk((short)rs.getInt("luk"));
                                equip.setMatk((short)rs.getInt("matk"));
                                equip.setWatk((short)rs.getInt("watk"));
                                equip.setAcc((short)rs.getInt("acc"));
                                equip.setAvoid((short)rs.getInt("avoid"));
                                equip.setJump((short)rs.getInt("jump"));
                                equip.setSpeed((short)rs.getInt("speed"));
                                equip.setWdef((short)rs.getInt("wdef"));
                                equip.setMdef((short)rs.getInt("mdef"));
                                equip.setHp((short)rs.getInt("hp"));
                                equip.setMp((short)rs.getInt("mp"));
                                equip.setUpgradeSlots((byte)rs.getInt("upgradeslots"));
                                MapleInventoryManipulator.addFromDrop(c, equip, "");
                                try {
                                        con = DatabaseConnection.getConnection();
                                        ps = con.prepareStatement("DELETE FROM mtsitems WHERE mtsitemid = ?");
                                        ps.setInt(1, mtsitemid);
                                        ps.execute();
                                } catch (SQLException e) {
                                    log.info("blah", e);
                                }
                                c.getSession().write(MaplePacketCreator.getMTSTransferSucceed(equip.getQuantity(), equip.getPosition()));
                                c.getSession().write(MaplePacketCreator.getMTSTransfer(c.getPlayer()));
                            } else {
                                Item item = new Item(rs.getInt("itemid"), (byte) 1, (short) rs.getInt("quantity"), -1);
                                item.setOwner(rs.getString("owner"));
                                IItem iItem = item.copy();
                                MapleInventoryManipulator.addFromDrop(c, iItem, "");
                                c.getSession().write(MaplePacketCreator.getMTSTransferSucceed(item.getQuantity(), item.getPosition()));
                                c.getSession().write(MaplePacketCreator.getMTSTransfer(c.getPlayer()));
                            }
                        }
                        rs.close();
                        ps.close();
                    } catch (SQLException e) {
                        log.info("bla", e);
                    }
                } else if (action == 9) {//add to cart
                    int mtsitemid = slea.readInt();
                    try {
                        Connection con = DatabaseConnection.getConnection();
                        PreparedStatement ps = con.prepareStatement("INSERT INTO cart"
						+ " (characterid, mtsitemid) "
						+ "VALUES (?, ?)");
                        ps.setInt(1, c.getPlayer().getId());
                        ps.setInt(2, mtsitemid);
                        ps.execute();
                    } catch (SQLException e) {
                        log.info("Error adding to cart", e);
                    }
                } else if (action == 10) {//cancel item from cart
                    int mtsitemid = slea.readInt();
                    try {
                        Connection con = DatabaseConnection.getConnection();
                        PreparedStatement ps = con.prepareStatement("DELETE FROM mtsitems WHERE mtsitemid = ?");
                        ps.setInt(1, mtsitemid);
                        ps.execute();
                    } catch (SQLException e) {
                        log.info("cancelling item from cart", e);
                    }
                } else if (action == 16) {//buy item
                    int mtsitemid = slea.readInt();
                    try {
                        Connection con = DatabaseConnection.getConnection();
                        PreparedStatement ps = con.prepareStatement("SELECT sellercharname,price,selleraccountname FROM mtsitems WHERE mtsitemid = ?");
                        ps.setInt(1, mtsitemid);
                        ResultSet rs = ps.executeQuery();
                        while (rs.next()) {
                            String charname = rs.getString("sellercharname");
                            String accountname = rs.getString("selleraccountname");
                            MapleCharacter player = c.getChannelServer().getPlayerStorage().getCharacterByName(charname);
                            int price = rs.getInt("price");
                            if (c.getPlayer().getCSPoints(0) >= price) {
                                if (player != null) {
                                    player.gainNX(price);
                                    player.dropMessage("One of your items in MTS has been sold for " + price + " NX");
                                } else {
                                    try {
                                        con = DatabaseConnection.getConnection();
                                        ps = con.prepareStatement("UPDATE accounts SET nxCash = (nxCash + ?) WHERE name = ?");
                                        ps.setInt(1, price);
                                        ps.setString(2, accountname);
                                        ps.executeUpdate();
                                    } catch (SQLException e) {
                                        log.info("Impossible error", e);
                                    }
                                }
                                c.getPlayer().gainNX(-price);
                            } else {
                                c.getSession().write(MaplePacketCreator.getMTSBuyFail());
                                return;
                            }
                            try {
                                con = DatabaseConnection.getConnection();
                                ps = con.prepareStatement("UPDATE mtsitems SET sellerid = ?, transfer = 1 WHERE mtsitemid = ?");
                                ps.setInt(1, c.getPlayer().getId());
                                ps.setInt(2, mtsitemid);
                                ps.executeUpdate();
                            } catch (SQLException e) {
                                log.info("Impossible error", e);
                            }
                        }
                        rs.close();
                        ps.close();
                    } catch (SQLException e) {
                        log.info("Error getting the mts item", e);
                    }

                    
                    c.getSession().write(MaplePacketCreator.getMTSTransfer(c.getPlayer()));
                    c.getSession().write(MaplePacketCreator.getMTSItems(c.getPlayer(), 4, 0));
                    c.getSession().write(MaplePacketCreator.getMTSTokens(c.getPlayer()));
                } else if (action == 17) {//buy item from cart
                    int mtsitemid = slea.readInt();
                } else if (action == 20) {//auction buy
                    int mtsitemid = slea.readInt();
                }
        }
}
